package com.itheima.api;

import com.itheima.tanhua.api.mongo.FriendApi;
import com.itheima.tanhua.pojo.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author 芝士雪豹
 * @create 2022/9/28/19:46
 */
@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long id, Long friendId) {
        //添加个人好友关系
        //调用temp 构建查询条件
        Query query = Query.query(Criteria.where("userId").is(id).and("friendId").is(friendId));
        //判断是否有盆友关系
        boolean exists = mongoTemplate.exists(query, Friend.class);
        if (!exists) {
            //没有就添加好友关系
            Friend friend = new Friend();
            friend.setFriendId(friendId);
            friend.setUserId(id);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        //添加好友的好友关系
        Query query1 = Query.query(Criteria.where("friendId").is(id).and("userId").is(friendId));
        boolean exists1 = mongoTemplate.exists(query1, Friend.class);
        if (!exists1) {
            Friend friend = new Friend();
            friend.setFriendId(id);
            friend.setUserId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }
    //查找 好友数据
    @Override
    public List<Friend> findByUserId(Long id, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(id)).
                skip((page - 1) * pagesize).
                limit(pagesize);
        return mongoTemplate.find(query,Friend.class);
    }
}
